
module Cms
  class ToolbarButton < Widget
    
    def action
      page = Page.new
      rendered = page.render
      #scripts = get_scripts page
      #p scripts[0].methods
      
      # FIXME remove the scripts somehow
      
      respond "
        jQuery('.desktopContainer').append('#{rendered.join().split("\n").join().split("'").join("\\'")}');
      "
      #/*#{scripts.collect { |s| s.innerHTML }.join }*/
    end
    
    def render
      e :script, "
          dcat_instance.oninit(function(Y) {
            
            jQuery('##{id}').click(function() {
              //jQuery.getScript('#{callback :action}');
              Y.io('#{callback :action}', {
                //data : 'state='+json_state,
                method: 'POST',
                on : {
                  complete : function(id, o, args) {
                    console.log(o);
                    eval(o.responseText);
                  }
                }
              });
            })
          });
      "
      super()
    end
    
    def get_scripts node
      scripts = []
      node.children.each { |e|
        if e.respond_to? :tagName
          if e.tagName == :script 
            scripts << e
            e.parent.children = e.parent.children - [e]
          end
        end
      }
      node.children.each { |e|
        scripts.push(*get_scripts(e))
      }
      scripts
    end
  end
end